//
//  CZEmotionPackage.swift
//  表情包数据
//
//  Created by youyoumacmini3 on 2017/8/7.
//  Copyright © 2017年 youyoumacmini3. All rights reserved.
//

import UIKit
import YYModel

/// 表情包模型
class CZEmotionPackage: NSObject {

    
    /// 表情包分组名
    var groupName: String?
    
    ///背景图片名称
    var bgImageName: String?
    
    
    
    /// 表情包目录，从目录下加载 info.plist 可以创建表情模型数组
    var directory: String? {
        didSet{
            // 当设置目录时，从目录下加载 info.plist
            guard let directory = directory,
                  let path = Bundle.main.path(forResource: "HMEmoticon.bundle", ofType: nil),
                  let bundle = Bundle(path: path),
                  let infoPath = bundle.path(forResource: "info.plist", ofType: nil, inDirectory: directory),
            let array = NSArray(contentsOfFile: infoPath) as? [[String: String]],
                  let models = NSArray.yy_modelArray(with: CZEmotion.self, json: array) as? [CZEmotion]
                else { return }
            
            // 遍历 models 数组，设置每个表情符号的目录
            for m in models {
                m.directory = directory
            }
            
            
            // 设置表情模型数组
            emotions += models
        
        }
    }
    
    /// 懒加载的表情模型空数组
    /// 使用懒加载可以避免后续解包
    lazy var emotions = [CZEmotion]()
    
    /// 表情页面数量
    var numOfPages: Int {
        return (emotions.count - 1) / 20 + 1 //代入数据推理下就知道为啥了
    }
    
    // 从懒加载的表情包中，按照 page 截取最多 20 个表情模型数组
    // eg:  有 26 个模型
    // page = 0,返回 0 ~ 20个模型
    // page = 1,返回 21 ~ 26个模型
    func emotion(page: Int) -> [CZEmotion] {
        
        let count = 20
        let location = page * count
        var length = count

        // 判断数组是否越界
        if location + length > emotions.count {
            length = emotions.count - location
        }
        
        let range = NSRange(location: location, length: length)
        // 截取数组子数组
        let subArr = (emotions as NSArray).subarray(with: range)
        
        return subArr as! [CZEmotion]
    }
    
    override var description: String {
        return yy_modelDescription()
    }
}
